package top.codedance.iotp.server.net.handle.listenner;

import cd.io.netty.channel.ChannelFuture;
import cd.io.netty.channel.ChannelFutureListener;
import top.codedance.iotp.server.net.WsServer;
import top.codedance.iotp.server.net.handle.WsReceiveHandler;
import top.codedance.iotp.server.net.handle.configuration.WsRouteConfig;
import top.codedance.iotp.server.net.handle.entity.ReceiverQueueEntity;

import java.util.*;

public class WsConnectionListener implements ChannelFutureListener {

    public void operationComplete(final ChannelFuture future) {
        if (future.isSuccess() && future.channel().isActive()) {
            Timer timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    if(!future.channel().isActive()){
                        timer.cancel();
                    }
                    Map<Short, WsReceiveHandler> wsReceiveHandlers = WsRouteConfig.getWsReceiveHandlers();
                    while (WsServer.localTaskReceiverQueue.size() > 0) {
                        try {
                            ReceiverQueueEntity receiverQueueEntity = WsServer.localTaskReceiverQueue.poll();
                            Set<Map.Entry<Short, WsReceiveHandler>> entries = wsReceiveHandlers.entrySet();
                            for (Map.Entry<Short, WsReceiveHandler> entry : entries) {
                                if (entry.getKey().equals(receiverQueueEntity.getReceiverCommand())) {
                                    if (WsServer.localTaskClients.containsKey(receiverQueueEntity.getReceiverCommand())) {
                                        Set<String> clients = WsServer.localTaskClients.get(receiverQueueEntity.getReceiverCommand());
                                        for (String c : clients) {
                                            entry.getValue().receive("-1", c, 0, receiverQueueEntity.getData().toJSONString());
                                        }
                                        break;
                                    }
                                }
                            }
                        }catch (Exception e){}
                    }
                }
            }, 1000l, 1000l * 10);
        }
    }
}
